package com.ssyc.gsk_teacher.adapter;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.makeramen.roundedimageview.RoundedImageView;
import com.ssyc.common.base.Constants;
import com.ssyc.common.bean.ResultInfo;
import com.ssyc.common.glide.ImageUtil;
import com.ssyc.common.http.HttpAdress;
import com.ssyc.common.http.HttpUtils;
import com.ssyc.common.manager.AccountUtils;
import com.ssyc.common.utils.GsonUtil;
import com.ssyc.common.utils.UiUtils;
import com.ssyc.common.view.dialog.CustomDialogManager;
import com.ssyc.gsk_teacher.R;
import com.ssyc.gsk_teacher.bean.LeaveInfo;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * 请假审批的列表适配器
 * Created by Administrator on 2018/7/4 0004.
 */

public class LeaveRvAdapter extends BaseQuickAdapter<LeaveInfo.DataBean, BaseViewHolder> {
    private Context context;
    private Handler handler;

    public LeaveRvAdapter(Context context, int layoutResId, @Nullable List<LeaveInfo.DataBean> data) {
        super(layoutResId, data);
        this.context = context;
        handler = new Handler();
    }

    @Override
    protected void convert(BaseViewHolder helper, LeaveInfo.DataBean item) {
        //创建时间
        TextView tvTime = helper.getView(R.id.tv_time);
        tvTime.setText(item.getCreateTime());

        //头像
        RoundedImageView ivHead = helper.getView(R.id.iv_head);
        ImageUtil.displayImage(context, ivHead, item.getIcon());


        //姓名
        TextView tvName = helper.getView(R.id.tv_name);
        tvName.setText(item.getStudentName());

        //请假时间
        TextView tvDate = helper.getView(R.id.tv_date);
        tvDate.setText(item.getBeginDate() + "~" + item.getEndDate());

        //请假事由
        TextView tvReason = helper.getView(R.id.tv_reason);
        tvReason.setText(item.getContent());

        //批准按钮
        Button btPz = helper.getView(R.id.bt_pz);
        if ("0".equals(item.getStatus())) {
            //未批准
            btPz.setBackgroundResource(R.drawable.teacher_dpz);
            btPz.setEnabled(true);
        } else if ("1".equals(item.getStatus())) {
            //已批准
            btPz.setBackgroundResource(R.drawable.teacher_ypz);
            btPz.setEnabled(false);
        }

        //联系家长按钮
        Button btLxjz = helper.getView(R.id.bt_lxjz);
        btLxjz.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //调用系统拨号
                String phone = item.getStudentId().toString().trim();
                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone));
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            }
        });

        //批准按钮的点击事件
        btPz.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                doRatifyAction(item, helper.getLayoutPosition());
            }
        });
    }

    /**
     * 批准
     *
     * @param item
     */
    private void doRatifyAction(LeaveInfo.DataBean item, int pos) {
        CustomDialogManager.show(context, "批准中...");

        Map<String, String> map = new HashMap<>();
        map.put("type", "3");
        map.put("acc", AccountUtils.getAccount(context));
        map.put("role", AccountUtils.getRole(context));
        map.put("apptoken", AccountUtils.getToken(context));
        map.put("row_id", item.getRowId() + "");
        map.put("platform", "8");

        Log.i("test","apptoken：" +AccountUtils.getToken(context)
        +"row_id:"+item.getRowId());

        HttpUtils.post(HttpAdress.TEACHERLEAVELIST, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                CustomDialogManager.dissmiss();
                UiUtils.Toast("批准失败,服务器异常", false);
            }

            @Override
            public void onResponse(String response, int id) {
                CustomDialogManager.dissmiss();
                if (!TextUtils.isEmpty(response)) {
                    ResultInfo info = null;
                    try {
                        info = GsonUtil.jsonToBean(response, ResultInfo.class);
                    } catch (Exception e) {
                        Log.i("test", Constants.PARSEDATAERROR);
                    }
                    Log.i("test","请假审批：" +response);
                    if (null != info) {
                        if ("200".equals(info.getState())) {
                            //返回成功
                            item.setStatus("1");
                            notifyRefresh(pos);
                            UiUtils.Toast("批准成功", false);
                        } else {
                            UiUtils.Toast("批准失败,返回异常码是:" + info.getState(), false);
                            Log.i("test", Constants.ERRORSTATE + info.getState());
                        }
                    } else {
                        Log.i("test", Constants.EMPTY);
                    }
                } else {
                    Log.i("test", Constants.EMPTY);
                }
            }
        });

    }

    /**
     * 在item点击事件中直接使用notifyDataSetChanged()
     * 解决java.lang.IllegalStateException: Cannot call this method while RecyclerView is computing a layout or scrolling
     *
     * @param pos
     */
    private void notifyRefresh(final int pos) {
        Runnable r = new Runnable() {
            public void run() {
                notifyItemChanged(pos);
            }
        };
        handler.post(r);
    }

    /**
     * 提供给Activity释放handler对象的方法,防止内存泄漏
     */
    public void releaseHandler() {
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
    }
}
